package com.mgface.framework;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;

import sun.misc.BASE64Encoder;

public class ExportPrivateKey {
    private static File exportedFile = new File("D:\\aaa");           



    public static void main(String args[]) throws Exception{    
    	// 读取keystore文件到KeyStore对象
        FileInputStream in = new FileInputStream("D:/mgface.keystore");
        KeyStore ks = KeyStore.getInstance("JKS");// JKS: Java Key StoreJKS，可以有多种类型
        ks.load(in, "123456".toCharArray());
        in.close();        
        BASE64Encoder encoder=new BASE64Encoder();    
        // 从keystore中读取证书和私钥
        String alias = "mgface";  // 记录的别名
        String pswd = "123456";    // 记录的访问密码        
        java.security.cert.Certificate cert = ks.getCertificate(alias);
        PublicKey publicKey = cert.getPublicKey();
        PrivateKey privateKey = (PrivateKey) ks.getKey(alias, pswd.toCharArray());
        String encoded=encoder.encode(privateKey.getEncoded());    
        FileWriter fw=new FileWriter(exportedFile);    
        fw.write("—–BEGIN PRIVATE KEY—–/n");    
        fw.write(encoded);    
        fw.write("/n");    
        fw.write("—–END PRIVATE KEY—–");    
        fw.close();  
    }    
}  